#!/bin/bash
# 创建linux根文件系统
# 使用qemu加载linux内核


ROOTFS_PATH=~/study/qemu/
if test ! -e $ROOTFS_PATH/linux/arch/x86/boot/bzImage; then
    echo "没有bzImage, 请编译x86架构linux内核"
    return
fi

if test ! -e $ROOTFS_PATH/busybox/_install/bin/busybox; then
    echo "还没有编译busybox"
    return
fi

file_info=$(file $ROOTFS_PATH/busybox/_install/bin/busybox)
# 判断busybox编译的结果是不是x86-64架构
if ! echo $file_info | grep -iq "x86-64"; then
  echo "Please compile busybox for x86-64"
  return
fi

dd if=/dev/zero of=$ROOTFS_PATH/rootfs.img bs=1M count=32
mkfs.ext4 $ROOTFS_PATH/rootfs.img
mkdir $ROOTFS_PATH/fs
sudo mount -t ext4 -o loop $ROOTFS_PATH/rootfs.img $ROOTFS_PATH/fs/

sudo cp -arf $ROOTFS_PATH/busybox/_install/* $ROOTFS_PATH/fs/  
sudo mkdir $ROOTFS_PATH/fs/proc
sudo mkdir $ROOTFS_PATH/fs/dev
sudo mkdir $ROOTFS_PATH/fs/etc
sudo mkdir $ROOTFS_PATH/fs/home
sudo mkdir $ROOTFS_PATH/fs/mnt
sudo cp -r $ROOTFS_PATH/busybox/examples/bootfloppy/etc/* $ROOTFS_PATH/fs/etc/
sudo chmod -R 777 $ROOTFS_PATH/fs
sudo umount $ROOTFS_PATH/fs

qemu-system-x86_64 -kernel $ROOTFS_PATH/linux/arch/x86_64/boot/bzImage \
                    -hda $ROOTFS_PATH/rootfs.img  \
                    -append "root=/dev/sda console=ttyS0 nokaslr" \
                    -nographic 


qemu-system-x86_64 -kernel $ROOTFS_PATH/linux/arch/x86_64/boot/bzImage \
                    -hda $ROOTFS_PATH/rootfs.img  \
                    -append "root=/dev/sda console=ttyS0 nokaslr" \
                    -nographic \
                    -virtfs local,path=./u-boot,mount_tag=host0,security_model=passthrough,id=host0